const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const dotenv = require('dotenv');
const path = require('path');

// Load environment variables
dotenv.config();

// Initialize LevelDB database
const { initializeDatabase } = require('./config/leveldb');
const LevelDBService = require('./services/LevelDBService');

// Create Express app
const app = express();

// Initialize database before starting the server
async function startServer() {
  try {
    await initializeDatabase();
    console.log('Database initialized successfully');
    
    // 初始化股票信息表
    await LevelDBService.initializeStockInfo();
    console.log('Stock info table initialized successfully');
    
    // 配置应用基础路径
    const basePath = process.env.BASE_PATH || '';

    // Middleware
    app.use(cors());
    // 配置 Helmet 以允许加载 CDN 资源和内联事件处理器
    app.use(
      helmet({
        contentSecurityPolicy: {
          directives: {
            defaultSrc: ["'self'"],
            styleSrc: ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net"],
            scriptSrc: ["'self'", "https://cdn.jsdelivr.net", "'unsafe-inline'"],
            scriptSrcAttr: ["'self'", "'unsafe-inline'"],
            imgSrc: ["'self'", "data:", "https:"],
            fontSrc: ["'self'", "https:", "data:"],
            objectSrc: ["'none'"],
            upgradeInsecureRequests: [],
          },
        },
      })
    );
    app.use(morgan('combined'));
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));

    // Serve static files with base path
    app.use(basePath, express.static(path.join(__dirname, '../public')));

    // Routes with base path
    app.get(basePath + '/', (req, res) => {
      res.json({ 
        message: 'Stock Quant Trading System API', 
        version: '1.0.0' 
      });
    });

    // Import and use routes with base path
    const stockRoutes = require('./routes/stocks');
    const tradeRoutes = require('./routes/trades');
    const userRoutes = require('./routes/users');
    const authRoutes = require('./routes/auth');
    const strategyRoutes = require('./routes/strategies');

    app.use(basePath + '/api/stocks', stockRoutes);
    app.use(basePath + '/api/trades', tradeRoutes);
    app.use(basePath + '/api/users', userRoutes);
    app.use(basePath + '/api/auth', authRoutes);
    app.use(basePath + '/api/strategies', strategyRoutes);

    // Start the stock data scheduler
    if (process.env.NODE_ENV !== 'test') {
      // 只在非测试环境中启动定时任务
      const stockDataScheduler = require('./services/StockDataScheduler');
      stockDataScheduler.start(60); // 每60分钟更新一次
    }

    // Error handling middleware
    app.use((err, req, res, next) => {
      console.error(err.stack);
      res.status(500).json({ 
        error: 'Something went wrong!',
        message: err.message 
      });
    });

    // 404 handler
    app.use((req, res) => {
      res.status(404).json({ 
        error: 'Route not found' 
      });
    });

    return app;
  } catch (error) {
    console.error('Failed to initialize database:', error);
    process.exit(1);
  }
}

// Export a function that returns a promise of the app
module.exports = { app: startServer() };